import { defineStore } from 'pinia'
import { deleteAddressAPI, getAddressListAPI, addAddressAPI, updateAddressAPI } from '@/apis/address'
import { ref } from 'vue'

export const useAddressStore = defineStore('address', () => {
	const addressList = ref([])  // 地址列表

	// 获取订单地址
	const getAddress = async () => {
		const res = await getAddressListAPI().then(res => res.data);
		addressList.value = res.result;
		addressList.value.forEach(item => {
			item.isDefault = item.isDefault === 0 ? true : false;
		})
	}

	// 修改默认地址
	const setDefalutAddress = (address) => {
		addressList.value.forEach(async (item) => {
			if (item.id === address.id)
				item.isDefault = true
			else {
				item.isDefault = false
			}
			await updateAddress({ ...item, isDefault: item.isDefault ? 0 : 1 })
		})
	}

	// 删除地址
	const deleteAddress = async (id) => {
		await deleteAddressAPI(id)
		await getAddress()
		// 设置默认地址
		setDefalutAddress(addressList.value[0])
	}

	// 添加地址
	const addAddress = async (address) => {
		await addAddressAPI(address)
	}
	const updateAddress = async (address) => {
		await updateAddressAPI(address.id, address)
	}
	return {
		addressList,
		getAddress,
		setDefalutAddress,
		deleteAddress,
		addAddress,
		updateAddress
	}
})